<template>
  <div>

    <el-card>
      <el-row :gutter="30">
        <el-col :span="5">
          <el-input placeholder="公告主题" v-model="searchName"></el-input>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="success" icon="el-icon-search" @click="handleSearchNotice" plain>搜索</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="warning" icon="el-icon-refresh-left" @click="handleResetNotice" plain>重置</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="primary" icon="el-icon-plus" @click="handleRelease" plain>发布</el-button>
        </el-col>
        <el-col :span="2" style="text-align:right">
          <el-button type="danger" icon="el-icon-delete" @click="batchDeleteNotice" plain>删除</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card>
      <el-row>
        <el-table
            stripe
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%">
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              prop="topic"
              label="公告主题"
              width="120">
          </el-table-column>
          <el-table-column
              prop="content"
              label="公告内容"
              width="180"
              :formatter="formatContent">
          </el-table-column>
          <el-table-column
              prop="author"
              label="发布者"
              width="120">
          </el-table-column>
          <el-table-column
              prop="createdate"
              label="发布时间"
              width="300">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createdate) }}
            </template>
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="145"
              header-align="center">
            <template slot-scope="scope">
              <div style="display: flex; justify-content: center;">
                <el-button @click="handleViewNotice(scope.row)" type="primary" plain icon="el-icon-chat-line-round" circle size="small"></el-button>
                <el-button type="danger" plain size="small" icon="el-icon-delete" circle @click="deleteNotice(scope.row)"></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row>
        <el-pagination
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="pageData.currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size=pageData.pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageData.total">
        </el-pagination>
      </el-row>
    </el-card>

    <el-dialog
        title="查看公告"
        :visible.sync="dialogVisible"
        width="60%"
        :before-close="handleClose">

      <el-form :model="noticeForm">
        <el-form-item label="公告主题:" :label-width="formLabelWidth">
          <span>{{ noticeForm.topic }}</span>
        </el-form-item>
        <el-form-item label="发布者:" :label-width="formLabelWidth">
          <span>{{ noticeForm.author }}</span>
        </el-form-item>
        <el-form-item label="公告内容:" :label-width="formLabelWidth">
          <span>{{ noticeForm.content }}</span>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
    <el-button type="primary" plain @click="dialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "NoticeViews",
  data() {
    return {
      noticeForm: {
        topic: '',
        content: '',
        author: '',
        createdate: '',
        id: ''
      },
      formLabelWidth: '90px',
      dialogVisible: false,
      currentSearchName: '',
      searchName: '',
      tableData: [],
      pageData:{
        currentPage:1,
        pageSize:5,
        total:0
      }
    }
  },
  created() {
    this.getNoticeList()
  },
  methods:{
    resetForm(){
      this.noticeForm = {
        topic: '',
        content: '',
        author: '',
        createdate: '',
        id: ''
      };
    },
    async handleViewNotice(row) {
      try {
        const { data: res } = await this.$axios.get("notice/getNoticeById", { params: { id: row.id } });
        this.noticeForm = res.data;
        this.dialogVisible = true;
      } catch (error) {
        console.error("获取公告详情失败", error);
        this.$message.error("获取公告详情失败");
      }
    },
    formatContent(row, column, cellValue) {
      if (cellValue.length > 40) {
        return cellValue.slice(0, 40) + '...';
      }
      return cellValue;
    },
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        timeZone: 'Asia/Shanghai',
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      });
    },
    handleRelease() {
      this.$router.push({ name: 'release' });
    },
    currentChange(val){
      this.pageData.currentPage=val
      this.getNoticeList(this.currentSearchName)
    },
    sizeChange(val){
      this.pageData.pageSize=val
      this.getNoticeList(this.currentSearchName)
    },
    async getNoticeList(topic='') {
      const params = {...this.pageData, topic: topic};
      const {data: res} = await this.$axios.get("notice/getNotice",{params})
      this.tableData=res.data.records
      this.pageData.total=res.data.total
    },
    handleSearchNotice() {
      this.pageData.currentPage = 1; // 搜索时重置页码
      this.currentSearchName = this.searchName;// 设置当前搜索关键字
      this.getNoticeList(this.searchName);
    },
    handleResetNotice(){
      this.searchName = '';
      this.currentSearchName = ''; // 重置当前搜索关键字
      this.pageData.currentPage = 1;
      this.getNoticeList()
    },
    deleteNotice(row){
      this.$confirm('此操作将永久删除该公告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const {data:res}=await this.$axios.get("notice/deleteById",{params:{id:row.id}})
        if (res.success){
          this.$message.success('删除成功')
          await this.getNoticeList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    batchDeleteNotice() {
      const selectedRows = this.$refs.multipleTable.selection;
      if (selectedRows.length === 0) {
        this.$message.warning('请选择要删除的公告');
        return;
      }
      this.$confirm('此操作将永久删除选中的公告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const ids = selectedRows.map(row => row.id);
        const { data: res } = await this.$axios.post("notice/batchDeleteNotice", ids);
        if (res.success) {
          this.$message.success('删除成功');
          await this.getNoticeList()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    }
  }
}
</script>

<style scoped>
.el-pagination{
  margin-top: 10px;
}
</style>